package com.zr.domain.caffeine;

import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    // 基础缓存：Key=userId，缓存空值防止穿透（unless过滤null）
    @Cacheable(value = "userCache", key = "#userId", unless = "#result == null")
    public User getUserById(String userId) {
        System.out.println("模拟数据库查询: " + userId);
        return fetchUserFromDB(userId); // 可能返回null
    }

    // 同步加载防止击穿（高并发下同一Key只允许一个线程加载）
    @Cacheable(value = "userCache", key = "#userId", sync = true)
    public User getUserByIdSync(String userId) {
        return fetchUserFromDB(userId);
    }

    // 更新用户后刷新缓存
    @CachePut(value = "userCache", key = "#user.userId")
    public User updateUser(User user) {
        System.out.println("模拟更新用户: " + user.getUserId());
        return user;
    }

    // 删除用户时清除缓存
    @CacheEvict(value = "userCache", key = "#userId")
    public void deleteUser(String userId) {
        System.out.println("模拟删除用户: " + userId);
    }

    // 带条件的缓存：仅当用户状态为激活时缓存
    @Cacheable(value = "userCache", key = "#userId", condition = "#result != null && #result.isActive()")
    public User getActiveUser(String userId) {
        User user = fetchUserFromDB(userId);
        return user != null && user.isActive() ? user : null;
    }

    // 模拟数据库查询（可能耗时或返回null）
    private User fetchUserFromDB(String userId) {
        // 实际业务中替换为DAO操作
        return userId.startsWith("1") ? new User(userId, "User-" + userId) : null;
    }
}